<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import dayjs from 'dayjs'
import {
  deleteImage,
  getImageByVideoDiagnoseId,
  getRoomId,
  getUserSig,
} from '@/services/videoDiagnose'
import { useMemberStore } from '@/stores'
import { baseURL } from '@/utils/http'

const query = defineProps<{
  videoDiagnoseId: number
  expectStart: string
  expectEnd: string
  doctorId: number
}>()
const videoDiagnoseId = ref(query.videoDiagnoseId)
const expectStart = ref(query.expectStart)
const expectEnd = ref(query.expectEnd)
const minioUrl = 'http://114.132.57.246:9000/hospital'
const uploadUrl = baseURL + '/video_diagnose/uploadImage'
const memberStore = useMemberStore()
//查询医生上线缓存中的RoomId需要使用doctorId
const doctorId = ref(query.doctorId)
const startOrEnd = ref('开始')
const enableBtn = ref(false)
//距离开始或者结束还差多少时间
const time = ref<number>(0)
//倒计时的时间对象
const timeData = ref({})
//文件列表
const fileList = ref<
  {
    filename: string
    thumb: string
    url: string
    type: 'image'
    status?: string
  }[]
>([])
const afterRead = (event: any) => {
  console.log(event)
  let token = memberStore.profile?.token

  //保存选中照片的数组
  let lists = event.file
  //模型层fileList数组元素数量
  let fileListLen = fileList.value.length

  //如果倒计时结束或者问诊已经开始了就不能再上传照片了
  if (time.value <= 0 || startOrEnd.value == '结束') {
    return
  }

  //把新选中的照片添加到模型层的fileList数组中
  lists.map((item: any) => {
    fileList.value.push({
      ...item,
      status: 'uploading',
      message: '上传中',
    })
  })

  for (let i = 0; i < lists.length; i++) {
    uni.uploadFile({
      url: `${uploadUrl}?token=${token}`,
      filePath: lists[i].url,
      name: 'file',
      formData: {
        videoDiagnoseId: videoDiagnoseId.value,
      },
      success: (res) => {
        //返回的是字符串，需要转换成JSON
        let filename = JSON.parse(res.data).filename
        //取出刚上传的成功文件的JSON对象
        let item = fileList.value[fileListLen]
        item['status'] = 'success'
        //因为删除文件的时候需要使用filename，所以把filename添加到JSON对象中
        item['filename'] = filename
        fileListLen++
      },
    })
  }
}
const deleteImageHandle = (event: any) => {
  //倒计时结束或者问诊开始，则无法删除照片
  if (time.value <= 0 || startOrEnd.value == '结束') {
    return
  }

  let filename = fileList.value[event.index].filename
  let data = {
    videoDiagnoseId: videoDiagnoseId.value,
    filename,
  }
  deleteImage(data).then((res) => {
    uni.showToast({
      icon: 'success',
      title: '文件删除成功',
    })
    fileList.value.splice(event.index, 1)
  })
}
const deleteAllImageHandle = () => {
  if (time.value <= 0 || startOrEnd.value == '结束') {
    return
  }
  uni.showModal({
    title: '提示信息',
    content: '您确定删除所有上传文件？',
    success: function (resp) {
      if (resp.confirm) {
        let data = {
          videoDiagnoseId: videoDiagnoseId.value,
        }
        deleteImage(data).then((res) => {
          uni.showToast({
            icon: 'success',
            title: '文件删除成功',
          })
          fileList.value = []
        })
      }
    },
  })
}

const countDownOnChange = (e: any) => {
  //当前倒计时的分钟数字
  let minutes = e.minutes
  //当前倒计时的秒钟数字
  let seconds = e.seconds

  if (minutes == 0 && seconds == 0) {
    //如果到了问诊开始的时间
    if (startOrEnd.value == '开始') {
      startOrEnd.value = '结束'
      enableBtn.value = true
      //更新时间差
      time.value = dayjs(expectEnd.value).valueOf() - new Date().getTime()
      //手机发出震动，并且弹出提示信息
      uni.vibrateLong({
        complete: function () {
          uni.showToast({
            icon: 'none',
            title: '请进入问诊室',
            duration: 2000,
          })
        },
      })
    } else {
      /*
       * 可能在问诊中，患者手机突然没电关机了。等到他充上电开机之后，
       * 重新进入到候诊页面，可能视频问诊已经过了结束时间，所以这种
       * 情况就不允许进入视频问诊页面
       */
      //不可以点击进按钮入问诊页面
      enableBtn.value = false
      uni.showToast({
        icon: 'none',
        title: '问诊已结束',
      })
    }
  }

  if (minutes < 10) {
    e.minutes = '0' + minutes
  }

  if (seconds < 10) {
    e.seconds = '0' + seconds
  }

  timeData.value = e
}

const roomId = ref('')
const enterHandle = () => {
  if (!enableBtn.value) {
    return
  }
  let data = {
    doctorId: doctorId.value,
  }
  getRoomId(data).then((res) => {
    let resultRoomId = res.result
    if (resultRoomId != null) {
      roomId.value = resultRoomId
      //查询TRTC的相关数据
      getUserSig().then((res) => {
        let userId = res.result.userId
        let userSig = res.result.userSig
        uni.navigateTo({
          url: `/video_diagnose/video_diagnose/video_diagnose?roomId=${resultRoomId}&userId=${userId}&userSig=${userSig}&expectEnd=${expectEnd.value}`,
        })
      })
    }
  })
}

onLoad(() => {
  let setTime = dayjs(expectStart.value).valueOf() - new Date().getTime()
  if (setTime > 0) {
    startOrEnd.value = '开始'
    enableBtn.value = false
  } else {
    setTime = dayjs(expectEnd.value).valueOf() - new Date().getTime()
    startOrEnd.value = '结束'
    enableBtn.value = true
  }
  console.log(setTime)
  time.value = setTime
  getImageByVideoDiagnoseId({ videoDiagnoseId: videoDiagnoseId.value }).then((res) => {
    let result = res.result
    for (let one of result) {
      fileList.value.push({
        filename: one.filename,
        thumb: `${minioUrl}/${one.path}`,
        url: `${minioUrl}/${one.path}`,
        type: 'image',
      })
    }
  })
})
</script>

<template>
  <view>
    <view class="main-container">
      <view>
        <u-count-down :time="time" format="mm:ss" autoStart @change="countDownOnChange">
          <view class="time">
            <text class="desc">距离问诊{{ startOrEnd }}</text>
            <text :class="startOrEnd == '结束' ? 'minute red' : 'minute'">{{
              timeData.minutes
            }}</text>
            <text class="unit">分</text>
            <text :class="startOrEnd == '结束' ? 'second red' : 'second'">{{
              timeData.seconds
            }}</text>
            <text class="unit">秒</text>
          </view>
        </u-count-down>
      </view>

      <view class="title">请上传诊断材料</view>
      <view class="files">
        <u-upload
          :fileList="fileList"
          @afterRead="afterRead"
          @delete="deleteImageHandle"
          multiple
          :maxSize="2 * 1024 * 1024"
          :maxCount="20"
          :previewFullImage="true"
        ></u-upload>
      </view>
      <view class="operate">
        <view class="btn red" @tap="deleteAllImageHandle">清空诊断材料</view>
        <view :class="enableBtn ? 'btn green' : 'btn gray'" @click="enterHandle">进入问诊室</view>
      </view>
    </view>
    <view class="desc-container">
      <view class="title">视频问诊说明</view>
      <view class="desc">
        <text class="num">1.</text>
        <text>
          在视频问诊之前以先上传相关的诊断材料照片，但是最多不能超过20张照片，而且每张照片不能超过2M体积。
        </text>
      </view>
      <view class="desc">
        <text class="num">2.</text>
        <text>
          视频问诊开始的时候，您可以点击【进入问诊室】按钮开始视频问诊。在视频问诊开始之前，请耐心等待。
        </text>
      </view>
      <view class="desc">
        <text class="num">3.</text>
        <text>
          建议您的手机连接WIFI网络，以保证最佳问诊质量。在问诊期间不要随便走动，避免网络信号波动，影响问诊音视频质量。
        </text>
      </view>
      <view class="desc">
        <text class="num">4.</text>
        <text>
          视频问诊仅作为初步诊断，存在误诊几率，不能以此当做准确诊断。建议您结合线下门诊的诊断结果及时就医。
        </text>
      </view>
      <view class="desc">
        <text class="num">5.</text>
        <text>
          如果遇到医疗系统技术故障或者其他不可抗力因素，无法进行视频问诊。请拨打【800-12388】客户热线，联系客服人员予以解决或者退款。
        </text>
      </view>
    </view>
  </view>
</template>

<style lang="less">
@import url('prepare_diagnose.less');
</style>
